import type { StateCreator } from 'zustand';
import type { SystemStore } from '../index';

// 应用布局类型
export type LayoutType = 'default' | 'compact' | 'wide';

// 应用设置接口
export interface AppSettings {
  layout: LayoutType;
  pageSize: number;
  showLineNumbers: boolean;
  enableAutoSave: boolean;
  autoSaveInterval: number; // 秒
  enableNotifications: boolean;
  soundEnabled: boolean;
  animationsEnabled: boolean;
  keyboardShortcuts: boolean;
}

// 编辑器设置
export interface EditorSettings {
  fontSize: number;
  fontFamily: string;
  tabSize: number;
  wordWrap: boolean;
  minimap: boolean;
  lineHeight: number;
  cursorStyle: 'line' | 'block' | 'underline';
}

// 显示设置
export interface DisplaySettings {
  density: 'comfortable' | 'compact' | 'spacious';
  gridLines: boolean;
  timestamps: boolean;
  avatars: boolean;
  borders: boolean;
}

// 设置状态接口
export interface SettingsState {
  settings: AppSettings;
  editorSettings: EditorSettings;
  displaySettings: DisplaySettings;
  isSettingsLoaded: boolean;
  settingsVersion: number;
}

// 设置Actions接口
export interface SettingsActions {
  // 应用设置
  updateSettings: (settings: Partial<AppSettings>) => void;
  updateSetting: <K extends keyof AppSettings>(
    key: K,
    value: AppSettings[K]
  ) => void;
  resetSettings: () => void;
  
  // 编辑器设置
  updateEditorSettings: (settings: Partial<EditorSettings>) => void;
  updateEditorSetting: <K extends keyof EditorSettings>(
    key: K,
    value: EditorSettings[K]
  ) => void;
  resetEditorSettings: () => void;
  
  // 显示设置
  updateDisplaySettings: (settings: Partial<DisplaySettings>) => void;
  updateDisplaySetting: <K extends keyof DisplaySettings>(
    key: K,
    value: DisplaySettings[K]
  ) => void;
  resetDisplaySettings: () => void;
  
  // 设置管理
  setSettingsLoaded: (loaded: boolean) => void;
  incrementSettingsVersion: () => void;
  loadSettings: () => Promise<void>;
  saveSettings: () => Promise<void>;
  exportSettings: () => string;
  importSettings: (settingsJson: string) => boolean;
  
  // 重置所有设置
  resetAllSettings: () => void;
}

// 设置Slice类型
export type SettingsSlice = SettingsState & SettingsActions;

// 默认应用设置
const defaultAppSettings: AppSettings = {
  layout: 'default',
  pageSize: 20,
  showLineNumbers: true,
  enableAutoSave: true,
  autoSaveInterval: 30,
  enableNotifications: true,
  soundEnabled: false,
  animationsEnabled: true,
  keyboardShortcuts: true,
};

// 默认编辑器设置
const defaultEditorSettings: EditorSettings = {
  fontSize: 14,
  fontFamily: 'Monaco, "SF Mono", Consolas, monospace',
  tabSize: 2,
  wordWrap: true,
  minimap: false,
  lineHeight: 1.5,
  cursorStyle: 'line',
};

// 默认显示设置
const defaultDisplaySettings: DisplaySettings = {
  density: 'comfortable',
  gridLines: false,
  timestamps: true,
  avatars: true,
  borders: true,
};

// 默认状态
const initialSettingsState: SettingsState = {
  settings: defaultAppSettings,
  editorSettings: defaultEditorSettings,
  displaySettings: defaultDisplaySettings,
  isSettingsLoaded: false,
  settingsVersion: 1,
};

// 创建设置Slice
export const createSettingsSlice: StateCreator<
  SystemStore,
  [['zustand/immer', never], ['zustand/devtools', never], ['zustand/persist', unknown], ['zustand/subscribeWithSelector', never]],
  [],
  SettingsSlice
> = (set, get) => ({
  // 初始状态
  ...initialSettingsState,

  // Actions
  updateSettings: (settings) => {
    set((state: SystemStore) => {
      state.settings = { ...state.settings, ...settings };
    });
  },

  updateSetting: (key, value) => {
    set((state: SystemStore) => {
      state.settings[key] = value;
    });
  },

  resetSettings: () => {
    set((state: SystemStore) => {
      state.settings = { ...defaultAppSettings };
    });
  },

  updateEditorSettings: (settings) => {
    set((state: SystemStore) => {
      state.editorSettings = { ...state.editorSettings, ...settings };
    });
  },

  updateEditorSetting: (key, value) => {
    set((state: SystemStore) => {
      state.editorSettings[key] = value;
    });
  },

  resetEditorSettings: () => {
    set((state: SystemStore) => {
      state.editorSettings = { ...defaultEditorSettings };
    });
  },

  updateDisplaySettings: (settings) => {
    set((state: SystemStore) => {
      state.displaySettings = { ...state.displaySettings, ...settings };
    });
  },

  updateDisplaySetting: (key, value) => {
    set((state: SystemStore) => {
      state.displaySettings[key] = value;
    });
  },

  resetDisplaySettings: () => {
    set((state: SystemStore) => {
      state.displaySettings = { ...defaultDisplaySettings };
    });
  },

  setSettingsLoaded: (loaded) => {
    set((state: SystemStore) => {
      state.isSettingsLoaded = loaded;
    });
  },

  incrementSettingsVersion: () => {
    set((state: SystemStore) => {
      state.settingsVersion += 1;
    });
  },

  loadSettings: async () => {
    try {
      const stored = localStorage.getItem('app-settings');
      if (stored) {
        const parsedSettings = JSON.parse(stored);
        set((state: SystemStore) => {
          state.settings = { ...defaultAppSettings, ...parsedSettings.settings };
          state.editorSettings = { ...defaultEditorSettings, ...parsedSettings.editorSettings };
          state.displaySettings = { ...defaultDisplaySettings, ...parsedSettings.displaySettings };
          state.isSettingsLoaded = true;
        });
      }
    } catch (error) {
      console.error('Failed to load settings:', error);
      set((state: SystemStore) => {
        state.isSettingsLoaded = true;
      });
    }
  },

  saveSettings: async () => {
    try {
      const currentState = get();
      const settingsToSave = {
        settings: currentState.settings,
        editorSettings: currentState.editorSettings,
        displaySettings: currentState.displaySettings,
        version: currentState.settingsVersion,
      };
      localStorage.setItem('app-settings', JSON.stringify(settingsToSave));
    } catch (error) {
      console.error('Failed to save settings:', error);
    }
  },

  exportSettings: () => {
    const currentState = get();
    const exportData = {
      settings: currentState.settings,
      editorSettings: currentState.editorSettings,
      displaySettings: currentState.displaySettings,
      version: currentState.settingsVersion,
      exportedAt: new Date().toISOString(),
    };
    return JSON.stringify(exportData, null, 2);
  },

  importSettings: (settingsJson) => {
    try {
      const importedData = JSON.parse(settingsJson);
      if (importedData.settings && importedData.editorSettings && importedData.displaySettings) {
        set((state: SystemStore) => {
          state.settings = { ...defaultAppSettings, ...importedData.settings };
          state.editorSettings = { ...defaultEditorSettings, ...importedData.editorSettings };
          state.displaySettings = { ...defaultDisplaySettings, ...importedData.displaySettings };
          state.settingsVersion = importedData.version || state.settingsVersion + 1;
        });
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to import settings:', error);
      return false;
    }
  },

  resetAllSettings: () => {
    set((state: SystemStore) => {
      state.settings = { ...defaultAppSettings };
      state.editorSettings = { ...defaultEditorSettings };
      state.displaySettings = { ...defaultDisplaySettings };
      state.settingsVersion += 1;
    });
  },
}); 